package com.banmao.youZone.util;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.banmao.youZone.entity.RequestProperty;
import jakarta.annotation.Resource;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;

// 打卡
@Slf4j
@Component
public class ClockInUtil {

    // 工具类禁止主动实例化
    private ClockInUtil() {
    }

    private static final String ClockURL = "https://c1.yonyoucloud.com/yonbip-hr-tmsign/attentance/" +
            "encryptSignIn";

    private static final String buildSignPostParams = "{\"longitude\":\"%s\"," +
            "\"latitude\":\"%s\"," +
            "\"address\":\"广东省广州市天河区俊华街193号靠近广东邮电职业技术学院(广州校区)\"," +
            "\"placeName\":\"广东邮电职业技术学院\",\"placeId\":\"1862706030807875586\"," +
            "\"accountId\":0,\"szId\":0," +
            "\"signTime\":%s," +
            "\"imei\":\"%s\"," +
            "\"deviceModel\":\"%s\"," +
            "\"deviceName\":\"%s\"," +
            "\"isRoot\":0,\"appName\":\"\",\"cheatType\":0}";


    private static Validator validator;

    @Resource(name = "validator")
    private void setValidator(Validator validator) {
        ClockInUtil.validator = validator;
    }

    public static HttpResponse clock(RequestProperty requestProperty) {
        if (requestProperty == null || StringUtils.isBlank(requestProperty.getAccessToken())) {
            HttpRequest request = HttpUtil.createGet("https://autodev.openspeech.cn/csp/api/v2.1/weather?openId=aiuicus" +
                    "&clientType=android&sign=android&city=%E4%B8%8A%E6%B5%B7" +
                    "&needMoreData=true&pageNo=1&pageSize=7");
            request.timeout(10000);

            if (requestProperty != null) {
                String userAgent = requestProperty.getUserAgent();
                if (StringUtils.isBlank(userAgent)) {
                    String deviceModel = StringUtils.isBlank(requestProperty.getDeviceModel()) ? "TEL-AN10" : requestProperty.getDeviceModel();
                    userAgent = String.format("esn_enterprise_develop/7.6.17 (Android; %s; %s; 10);", "其他", deviceModel);
                }

                request.header("User-Agent", userAgent);
            }
            return request.execute();
        }

        Set<ConstraintViolation<RequestProperty>> violations = validator.validate(requestProperty);
        if (!violations.isEmpty()) {
            String errMsg = violations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(";"));
            throw new IllegalArgumentException("校验未通过:" + errMsg);
        }

        HttpRequest request = HttpUtil.createPost(ClockURL + "?clientV=" + requestProperty.getVercode());
        request.timeout(10000);

        String userAgent = requestProperty.getUserAgent();
        if (StringUtils.isBlank(userAgent)) {
            String deviceModel = StringUtils.isBlank(requestProperty.getDeviceModel()) ? "TEL-AN10" : requestProperty.getDeviceModel();
            userAgent = String.format("esn_enterprise_develop/7.6.17 (Android; %s; %s; 10);", "其他", deviceModel);
        }

        HashMap<String, String> headers = new HashMap<>() {{
            put("a00", requestProperty.getA00());
            put("multilingualFlag", requestProperty.getMultilingualFlag());
            put("encrypted_user_id", requestProperty.getEncryptedUserId());
            put("yht_access_token", requestProperty.getYhtAccessToken());
            put("tenantId", requestProperty.getYtenantId());
            put("locale", requestProperty.getLocale());
            put("timezone", requestProperty.getTimezone());
            put("language", requestProperty.getLanguage());
            put("languages", requestProperty.getLanguages());
            put("defaultLocale", requestProperty.getDefaultLocale());
            put("orgId", requestProperty.getOrgId());
            put("defaultOrg", requestProperty.getDefaultOrg());
            put("newArch", requestProperty.getNewArch());
            put("n_f_f", requestProperty.getNFf());
            put("Content-Type", "application/x-www-form-urlencoded");
            put("Host", "c1.yonyoucloud.com");
            put("Accept-Encoding", "gzip");
        }};

        request.addHeaders(headers);

        request.header("User-Agent", userAgent);

        String requestBody = buildBody(requestProperty);

        request.body(requestBody);

        log.info("[{}]发起打卡请求,request:{}", requestProperty.getUserId(), JSON.toJSONString(request));
        log.info("[{}]发起打卡请求,requestBody:{}", requestProperty.getUserId(), requestBody);
        log.info("[{}]发起打卡请求,requestHeaders:{}", requestProperty.getUserId(), JSON.toJSONString(headers));

        HttpResponse response = request.execute();

        log.info("[{}]打卡请求得到响应,response:{}", requestProperty.getUserId(), JSON.toJSONString(response));
        log.info("[{}]打卡请求得到响应,responseBody:{}", requestProperty.getUserId(), response.body());

        if (response.getStatus() == 200) {
            log.info("[{}]打卡成功", requestProperty.getUserId());
        } else {
            log.error("[{}]打卡失败", requestProperty.getUserId());
        }

        return response;
    }

    protected static String buildBody(RequestProperty requestProperty) {

        /**
         * 打卡参数:{"longitude":"113.36496","latitude":"23.135351",
         * "address":"广东省广州市天河区俊华街193号靠近广东邮电职业技术学院(广州校区)",
         * "placeName":"广东邮电职业技术学院","placeId":"1862706030807875586",
         * "accountId":0,"szId":0,"signTime":1737337043655,"imei":"2c486ad070fd91869a15f7bd1f83ae0f",
         * "deviceModel":"TEL-AN10","deviceName":"华为","isRoot":0,"appName":"","cheatType":0}
         */
        String longitude = "113.3649" + RandomUtil.randomInt(1, 10000);
        String latitude = "23.1353" + RandomUtil.randomInt(1, 10000);

        String imei = StringUtils.isBlank(requestProperty.getImei()) ? "2c486ad070fd91869a15f7bd1f83ae0f" : requestProperty.getImei();
        String deviceModel = StringUtils.isBlank(requestProperty.getDeviceModel()) ? "TEL-AN10" : requestProperty.getDeviceModel();
        String deviceName = StringUtils.isBlank(requestProperty.getDeviceName()) ? "华为" : requestProperty.getDeviceName();

        String format = String.format(buildSignPostParams, longitude, latitude, System.currentTimeMillis(),
                imei, deviceModel, deviceName);

        log.info("[{}]打卡参数:{}", requestProperty.getUserId(), format);

        String encryptedAttentance = AesUtil.aesEncode(AesUtil.SIGN_KEY, format);

        HashMap<String, String> params = new HashMap<>() {{
            put("encryptedAttentance", encryptedAttentance);
            put("qz_id", requestProperty.getQzId());
            put("vercode", requestProperty.getVercode());
            put("appType", "1");
            put("language", "zhs");
            put("agent_id", "uspace");
            put("uspace_product_line", "app");
            put("access_token", requestProperty.getAccessToken());
        }};

        StringBuilder sb = new StringBuilder();

        TreeMap<String, String> treeMap = ComputeUtil.sortTreeMapWithKT(params, requestProperty);
        Set<String> keys = treeMap.keySet();

        Iterator<String> iterator = keys.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            if (treeMap.get(key) == null) {
                continue;
            }
            sb.append(key).append("=").append(treeMap.get(key));
            if (iterator.hasNext()) {
                sb.append("&");
            }
        }

        return sb.toString();
    }

}
